package com.luych.toolbox.gateway.center.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.toolbox.common.event.base.service.WebSocketTaskRemoteApplicationEvent;
import com.luych.toolbox.gateway.center.websocket.WebSocketCache;
import com.luych.toolbox.gateway.center.websocket.WebSocketEndPoint;
import com.luych.toolbox.gateway.center.websocket.WebSocketMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;

@Component
public class WebSocketTaskListener implements ApplicationListener<WebSocketTaskRemoteApplicationEvent> {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketTaskListener.class);

    private final ObjectMapper objectMapper;
    private final WebSocketEndPoint webSocketEndPoint;

    @Autowired
    public WebSocketTaskListener(ObjectMapper objectMapper, WebSocketEndPoint webSocketEndPoint) {
        this.objectMapper = objectMapper;
        this.webSocketEndPoint = webSocketEndPoint;
    }

    @Override
    public void onApplicationEvent(WebSocketTaskRemoteApplicationEvent event) {
        for (Map.Entry<String, Session> sessionEntry : WebSocketCache.getSessions().entrySet()) {
            WebSocketMessage message = new WebSocketMessage(event.getTask());
            try {
                webSocketEndPoint.onSend(sessionEntry.getKey(), objectMapper.writeValueAsString(message));
            } catch (IOException e) {
                logger.error("websocket send event, userId: {}, error: {}", sessionEntry.getKey(), e.getMessage(), e);
            }
        }
    }
}
